const Axios = require("axios");
const fs = require('fs');

class Bilibili {
  constructor() {
    this.axios = new Axios.create({
      headers: {
        "Content-Type": "application/json",
        "accept-language": "zh-CN,zh;q=0.9",
        "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
      },
    });
  }

  // ret: {bvid, aid, cid, pic_url, title, duration, author}
  async parseInfoFromHTML(html) {
    const frontIndex = html.indexOf("videoData");
    const EndIndex = html.indexOf("upData");
    if (frontIndex === -1 || EndIndex === -1) reject("NO_MATCH");
    html = html.substring(0, EndIndex - 2).slice(frontIndex + 11);
    try {
      html = JSON.parse(html);
      html = {
        bvid: html.bvid,
        aid: html.aid,
        cid: html.cid,
        pic_url: html.pic,
        title: html.title,
        duration: html.duration,
        author: html.owner.name,
      };
    } catch (e) {
      reject("NO_DATA");
    };
    return html;
  }

  // vid_info: {url, eq, fnval, aid, bvid}
  async getAudioDownloadUrl(config) { 
    return new Promise((resolve, reject) => {
      if(!config.cid||!config.bvid) reject("NULL_CFG");
      this.axios.get("https://api.bilibili.com/x/player/playurl", {
        params: {
          otype: "json",
          cid: config.cid,
          bvid: config.bvid,
          ep_id: config.ep_id ?? null,
          qn: config.eq ?? 80,
          fnval: config.fnval ?? 80,
        },
        headers: {
          cookie: "0763dbab%2C1725548021%2C3f607%2A32CjDTtDjJsBdGEwO4AFtmqqT86z_boc7GJBUnFNDsQXyiXhG9jMjtZFktX2Aq5EfekQcSVjF1RE55d0xNaFM4S0hoMnl1YzV5THhiZHZlYmxqQUgyZUJRRks5cEFFX0ItOTlleHRkeUwtQUZEemd3LVdCbllBOXlGNnVwdExKNndMX1FRcHM2OC13IIEC",
          referer: config.url
        }
      }).catch(err=>reject(err.data))
        .then(res=>{
          if (!res.data || !res.data.data || !res.data.data.dash || !res.data.data.dash.audio) reject("NULL_RES");
          resolve(res.data.data.dash.audio[0].baseUrl);
        });
    })
  }

  async downloadAudioByUrl(download_url) {
    return new Promise((resolve, reject) => {
      this.axios.get(download_url, {
        headers: {
          "accept": "*/*",
          "accept-encoding": "identity",
          "origin": "https://www.bilibili.com",
          "range": "bytes=0-"
        }
      }).then(res => {
        console.log(res.headers['content-type']);
        resolve()
        // const contentType = res.headers['content-type'];
        // if (contentType !== 'audio/mpeg' && contentType !== 'application/octet-stream') {
        //   reject('Invalid file type');
        //   return;
        // }
        // const fileName = `audio_${this.bvid}.mp3`;
        // fs.writeFileSync(fileName, res.data);
        // resolve(fileName);
      })
      .catch(error => {
        reject(error);
      });
    });
  }

  async getRawInfoHTML(url) {
    return this.axios.get(url);
  }
}

module.exports = Bilibili;